package pl.omega.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.ui.ExpectedConditions;

import pl.omega.selenium.model.Film;

public class FilmListPage extends InternalPage {

	public FilmListPage(PageManager pages) {
		super(pages);
	}
	
	public FilmListPage ensurePageLoaded() {
	    super.ensurePageLoaded();
	    wait.until(presenceOfElementLocated(By.id("search")));
	    return this;
	}
	
	@FindBy(id = "q")
	private WebElement searchField;
	
	@FindBy(id = "loading")
	private WebElement loading;

	@FindBy(className = "movie_box")
	private List<WebElement> filmList;
	
	public FilmListPage search(String q) {
		searchField.sendKeys("");
		searchField.clear();
		searchField.sendKeys(q + Keys.RETURN);
		WebElement loading = driver.findElement(By.id("loading"));
	    driver.findElement(By.id("q")).clear();
	    driver.findElement(By.id("q")).sendKeys("seven"+Keys.RETURN);
	    //wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOf(loading)));
	    wait.until(ExpectedConditions.visibilityOf(loading));
		return this;
	}
	
	public int getFilmCount() {
		return filmList.size();
	}
	
	public FilmViewPage clickFilm() {
		filmList.get(0).click();
		return pages.filmViewPage;
	}
	
	public List<Film> getFilms() {
		List<Film> films = new ArrayList<Film>();
		for(WebElement film : filmList) {
			// TODO add fields to Film
			films.add(new Film());
		}
		return films;
	}
}
